import React, { useEffect, useState } from 'react';
import { mockData } from '../utils/mockData';

const HighFrequencyWords = () => {
  const [words, setWords] = useState([]);

  useEffect(() => {
    setWords(mockData.highFrequencyWords);
    const interval = setInterval(() => {
      // 模拟数据更新
      setWords(prevWords => {
        // 简单地重新排列数据以模拟更新
        const shuffled = [...prevWords];
        for (let i = shuffled.length - 1; i > 0; i--) {
          const j = Math.floor(Math.random() * (i + 1));
          [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
      });
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  const formatWord = (word, maxLength) => {
    if (!word) return "";

    let formatted = word.trim();
    if (formatted.length > maxLength) {
      formatted = formatted.substring(formatted.length - maxLength);
    }

    return formatted;
  };

  const renderWordsGrid = () => {
    // 只取前18个高频词
    const topWords = words.slice(0, 18);

    return topWords.map((item, index) => {
      const displayWord = formatWord(item.word, 5);

      return (
        <div 
          key={index} 
          className="word-item"
          style={{
            background: index < 3 ? 
              (index === 0 ? 'rgba(255, 198, 64, 0.2)' : 
               index === 1 ? 'rgba(36, 187, 236, 0.2)' : 
               'rgba(36, 211, 154, 0.2)') : 
              'rgba(10, 58, 124, 0.4)',
            borderColor: index < 3 ? 
              (index === 0 ? '#ffc640' : 
               index === 1 ? '#24bbec' : 
               '#24d39a') : 
              'rgba(36, 187, 236, 0.15)'
          }}
        >
          <div className="word-text" title={item.word}>{displayWord}</div>
          <div 
            className="word-count"
            style={{
              background: index < 3 ? 
                (index === 0 ? 'linear-gradient(to right, #ffc640, #ff9800)' : 
                 index === 1 ? 'linear-gradient(to right, #24bbec, #1d6fa0)' : 
                 'linear-gradient(to right, #24d39a, #1da971)') : 
                'linear-gradient(to right, #ffc640, #ff9800)',
              WebkitBackgroundClip: 'text',
              WebkitTextFillColor: 'transparent'
            }}
          >
            {item.word_count}
          </div>
        </div>
      );
    });
  };

  return (
    <div className="high-frequency-words">
      <div className="words-header">
      </div>
      <div className="words-grid">
        {renderWordsGrid()}
      </div>
    </div>
  );
};

export default HighFrequencyWords;